﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Web;
using ContractorTimesheet.DataModel;
using SimpleCrypto;

namespace ContractorTimesheet.Repository
{
    public class UserRepository : BaseRepository
    {
        TimesheetDBModel dataModel = new TimesheetDBModel();

        public User Get(int id)
        {
            return dataModel.Users.Single(o => o.Id == id);
        }

        public IList<User> GetAllUsers()
        {
            return dataModel.Users.Where(m => m.IsAdmin == false).ToList();
        }

        public IList<User> GetAllActiveUsers()
        {
            return dataModel.Users.Where(m => m.IsAdmin == false && m.IsActive == true).ToList();
        }

        public void Add(User user)
        {
            try
            {
                dataModel.Users.Add(user);

                dataModel.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                throw new Exception(GetErrorMessage(ex));
            }
        }

        public async void DeleteAsync(int id)
        {
            User user = dataModel.Users.Single(o => o.Id == id);

            dataModel.Users.Remove(user);

            await dataModel.SaveChangesAsync();
        }

        public User Validate(string username, string password)
        {
            User user = dataModel.Users.SingleOrDefault(o => (o.Firstname + "_" + o.Lastname).ToLower() == username.ToLower());

            if (user != null && user.Password == new PBKDF2().Compute(password, user.PasswordSalt))
                return user;

            return null;
        }

        public void UpdateUser(User user)
        {
            User oldUser = dataModel.Users.Single(o => o.Id == user.Id);

            oldUser.Firstname = user.Firstname;
            oldUser.Lastname = user.Lastname;
            oldUser.Email = user.Email;
            oldUser.IsActive = user.IsActive;
            oldUser.BadgeNo = user.BadgeNo;
            oldUser.PO = user.PO;
            oldUser.Password = user.Password;
            oldUser.PasswordSalt = user.PasswordSalt;

            dataModel.SaveChanges();
        }
    }
}